/**
 * Created by Spring on 2017/4/7.
 */
({
  doInit:function(cmp, event, helper){
    console.log('into ......doinit...');
    // $A.util.toggleClass 是一个开关,开是加上,关是移除
    $A.util.toggleClass(cmp.find("comfirmDialog"), "slds-fade-in-open");
    $A.util.toggleClass(cmp.find("comfirmDialogBackdrop"), "slds-backdrop--open");
    //大部分需要用JS构建出一个对象,类比如我们之前在写VF 和 Apex 时,在Apex中定一个对象 在VF
    //中当做筛选条件,自已体会
    var acc = cmp.get('v.acc');
    if(acc == null){
      acc = new Object();
      acc.name = '';
      acc.AccountSource = '';
      cmp.set('v.acc', acc);
    }
    helper.loadAccount(cmp);
  },

  searchAccount:function(cmp, event, helper){
    console.log(cmp.get("v.acc"));
    //cmp.find 只能找aura:id
    var spinner = cmp.find("mySpinner");
    $A.util.toggleClass(spinner, "slds-hide");
    helper.loadAccount(cmp);
  },

  addRow:function(cmp){
    var acc = new Object();
    acc.name = '';
    acc.accountSource = '';
    acc.description = '';
    acc.id = null;
    acc.flag = false;

    var accList = cmp.get("v.accountList");
    accList.push(acc);
    cmp.set("v.accountList", accList);
  },

  confirmDel:function(cmp, event, helper){
    $A.util.toggleClass(cmp.find("comfirmDialog"), "slds-fade-in-open");
    $A.util.toggleClass(cmp.find("comfirmDialogBackdrop"), "slds-backdrop--open");
  },

  confirmDelTrue:function(cmp, event, helper){
    $A.util.toggleClass(cmp.find("comfirmDialog"), "slds-fade-in-open");
    $A.util.toggleClass(cmp.find("comfirmDialogBackdrop"), "slds-backdrop--open");

    var accList = cmp.get("v.accountList");
    var newAccList = new Array();
    var delAccList = new Array();//后台删除

    for(var index = 0; index < accList.length; index++){
      //有那些被选中了
      if(!accList[index].flag){
        newAccList.push(accList[index]);
      }
      //只有id不为空的才到后台删除
      if(accList[index].flag && accList[index].id != null){
        delAccList.push(accList[index].id);
      }
    }
    //重新设置集合  PS:这里有问题可以优化
    cmp.set("v.accountList", newAccList);
    //当需要通过数据库删除的记录不为空时,才调整helper方法去后台删除
    if(delAccList.length != 0){
      helper.delAccount(cmp, delAccList, newAccList)
    }
  },

  saveAll:function(cmp, event, helper){
    var accList = cmp.get("v.accountList");
    var flag = false;
    //检查名字是否为空
    for(var i = 0; i< accList.length; i++){
      if(accList[i].name == ''){
        flag = true;
        break;
      }
    }
    if(flag){
      //toast是一个消息弹出框,非模态框,是一个事件,只能在Lighting框加中使用
      var toastEvent = $A.get("e.force:showToast");
      toastEvent.setParams({
        "title": "",
        "message": "客户名称不能为空!",
        "type":"error"
      });
      toastEvent.fire();
    } else {
      helper.saveAccount(cmp);
    }
  }

})